package com.example.lotterysystem.service.activitystatus.operator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.lotterysystem.common.enums.ActivityPrizeStatusEnum;
import com.example.lotterysystem.common.enums.ActivityStatusEnum;
import com.example.lotterysystem.dao.dataobject.Activity;
import com.example.lotterysystem.dao.dataobject.ActivityPrize;
import com.example.lotterysystem.mapper.ActivityMapper;
import com.example.lotterysystem.mapper.ActivityPrizeMapper;
import com.example.lotterysystem.service.dto.TransferActivityStatusDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ActivityOperator extends AbstractActivityOperator{

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 2;
    }

    @Override
    public Boolean checkTransfer(TransferActivityStatusDTO statusDTO) {
        Long activityId = statusDTO.getActivityId();
        ActivityStatusEnum activityStatus = statusDTO.getTargetActivityStatus();
        if(activityStatus == null || activityId == null){
            return false;
        }
        Activity activity = activityMapper.selectById(activityId);
        if(activity == null){
            return false;
        }
        if(activityStatus.name().equalsIgnoreCase(activity.getStatus())){
            return false;
        }
        Long count = activityPrizeMapper.selectCount(
                new QueryWrapper<ActivityPrize>()
                        .eq("activity_id", activityId)
                        .eq("status", ActivityPrizeStatusEnum.INIT.name()));
        if(count > 0){
            return false;
        }
        return true;
    }

    @Override
    public Boolean transfer(TransferActivityStatusDTO statusDTO) {
        try {
            // 将活动状态改为已完成，(可将同时将剩余未中奖的人员数量也改为已完成)
            activityMapper.updateStatus(statusDTO.getActivityId(),
                    statusDTO.getTargetActivityStatus().name());

            return true;
        } catch (Exception e){
            return false;
        }
    }
}
